package com.share.zabbix.method;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.share.zabbix.request.ZabbixRequest;
import com.share.zabbix.request.ZabbixRequestBuilder;
import com.share.zabbix.response.ZabbixResponseHost;
import com.share.zabbix.response.ZabbixResponseHostgroup;

import cn.hutool.core.util.StrUtil;

public class ZabbixHostMethod extends ZabbixBaseMethod {

	public static List<ZabbixResponseHost> getHost(String hostid, String groupid) {
		ZabbixRequest request = ZabbixRequestBuilder.newBuilder().method("host.get").extendOutput().build();
		if (!StrUtil.isEmpty(hostid))
			request.putParam("hostids", hostid);
		if (!StrUtil.isEmpty(groupid))
			request.putParam("groupids", groupid);
		try {
			JSONObject response = call(request);
			Gson gson = new GsonBuilder().create();
			List<ZabbixResponseHost> hostList = gson.fromJson(response.getJSONArray(ZABBIX_KEY_RESULT).toString(),
					new TypeToken<ArrayList<ZabbixResponseHost>>() {
					}.getType());
			return hostList;
		} catch (Exception e) {
			log.info("Zabbix查询主机失败！");
		}
		return null;
	}

	/**
	 * zabbix获取主机组
	 * 
	 * @param name
	 * @return
	 */
	public static List<ZabbixResponseHostgroup> getHostgroup(String name) {
		ZabbixRequest request = ZabbixRequestBuilder.newBuilder().method("hostgroup.get").extendOutput()
				.paramEntry("selectHosts", "extend").build();
		if (!StrUtil.isEmpty(name)) {
			JSONObject filter = new JSONObject();
			filter.put("name", name);
			request.putFilter(filter);
		}

		JSONObject response = call(request);
		try {
			String result = response.getJSONArray(ZABBIX_KEY_RESULT).toJSONString();
			Gson gson = new GsonBuilder().create();
			List<ZabbixResponseHostgroup> hostgroupList = gson.fromJson(result,
					new TypeToken<ArrayList<ZabbixResponseHostgroup>>() {
					}.getType());
			return hostgroupList;
		} catch (Exception e) {
			return null;
		}
	}
}
